package com.odm.communitymanage.ui

import android.Manifest
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.leaf.library.StatusBarUtil
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseActivity
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.LoginRegisterCallback
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.ui.login.LoginFragment
import com.odm.communitymanage.ui.mine.MineFragment
import com.odm.communitymanage.ui.notifications.NotificationsFragment
import com.odm.communitymanage.widget.CommonDialog
import com.rxjava.rxlife.lifeOnMain
import kotlinx.android.synthetic.main.activity_main.*
import rxhttp.wrapper.param.RxHttp


class MainActivity : BaseActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        KeyboardUtils.clickBlankArea2HideSoftInput()
        StatusBarUtil.setColor(this, resources.getColor(R.color.status_bar_color))
        StatusBarUtil.setDarkMode(this)
        setContentView(R.layout.activity_main)
        registerLiveEventObserve()

        if(SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_PHONE_NUMBER , "") == ""){
            loadRootFragment(R.id.fl_container,LoginFragment())
        }else if(findFragment(HomeFragment::class.java) == null){
            //若已经完成了一次登录则，直接进入首页
//            refreshCookieState()
            loadHome()

            loadRootFragment(R.id.fl_container,HomeFragment())
//            loadMultipleRootFragment(R.id.fl_container,0,HomeFragment(),NotificationsFragment(),MineFragment())
        }
    }

    private fun registerLiveEventObserve(){
        LiveEventBus.get("loadHome", String::class.java)
            .observeSticky(this, Observer<String>{
                    loadHome()
        })

        //收到隐藏底部导航栏事件
        LiveEventBus.get(Constants.EVENT_HIDE_NAVIGATION, String::class.java)
            .observeSticky(this, Observer<String>{
                 it?.let {
                     bnvContainer.visibility = View.GONE
                 }
            })

    }

    fun initViews(){
        //初始化底部导航栏
        bnvContainer.visibility  = View.VISIBLE
        bnvContainer.enableAnimation(false)
        bnvContainer.enableItemShiftingMode(false)
        bnvContainer.enableShiftingMode(false)
        //默认选中第一项
        bnvContainer.currentItem = BottomItems.HOME.ordinal
        bnvContainer.getBottomNavigationItemView(BottomItems.HOME.ordinal).setOnClickListener {
            //切换到首页管理页面且切换Item
            if(bnvContainer.currentItem != BottomItems.HOME.ordinal){
                bnvContainer.currentItem = BottomItems.HOME.ordinal
                replaceFragment(HomeFragment() , false)
            }
        }
        bnvContainer.getBottomNavigationItemView(BottomItems.NOTIFICATION.ordinal).setOnClickListener {
            //通知页面
            if(bnvContainer.currentItem != BottomItems.NOTIFICATION.ordinal) {
                bnvContainer.currentItem = BottomItems.NOTIFICATION.ordinal
                replaceFragment(NotificationsFragment(), false)
            }
        }

        bnvContainer.getBottomNavigationItemView(BottomItems.MINE.ordinal).setOnClickListener {
            //我的页面
            if(bnvContainer.currentItem != BottomItems.MINE.ordinal) {
                bnvContainer.currentItem = BottomItems.MINE.ordinal
                replaceFragment(MineFragment(), false)
            }
        }

    }

    /**
     * 进入首页的初始化准备
     */
    fun loadHome(){
         initViews()
         requestPermissions()
         requestCameraPermission()
     }

    /**
     * 获取Cookie保持登录状态
     */
    fun refreshCookieState(){
        RxHttp.get(ApiService.GET_CHECK_CODE +
                SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_PHONE_NUMBER , "")
                + "/12345")
            .asObject(LoginRegisterCallback::class.java)
            .lifeOnMain(this)
            .subscribe({
                if(it.code == 1){
                    //已注册了，直接调用登录请求,然后存储返回的小区信息和用户名,身份证件号
//                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_COMMUNITY_NAME , it.data.villageName)
                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_NAME , it.data.name)
                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_ID_CARD , it.data.idcard)
                }
            },{
                ToastUtils.showLong(it.message)
                LogUtils.e(it.message)
            })
    }

    /**
     * 申请文件读写权限
     */
    private fun requestPermissions(){


        if(! PermissionUtils.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            PermissionUtils.permission(PermissionConstants.STORAGE)
                .request()
        }
    }

    /**
     * 申请相机权限
     */
    private fun requestCameraPermission(){
        if(! PermissionUtils.isGranted(Manifest.permission.CAMERA)){
            PermissionUtils.permission(  PermissionConstants.STORAGE , PermissionConstants.CAMERA  )
                .request()
        }
    }

    public enum class BottomItems{
        HOME,
        NOTIFICATION,
        MINE
    }

}
